#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author  : ganuoxun
# @description : 数据中间层api

import datetime
from typing import List
from fastapi import APIRouter, Body
from apps.database import bulk_write_dwm, get_dwm, get_dwm_by_id
from apps.models.MiddleModel import WorkListModel
from apps.models.QueryModel import QuerySchema
from apps.models.ResponseModel import error, success

work_list_collection = 'cclp_dwm_work'
modify_collection = 'cclp_dwm_modify'

router = APIRouter()


@router.post("/work_list/get")
async def work_list_get(query: QuerySchema = Body(...)):
    try:
        results = await get_dwm(work_list_collection,
                                query.get_filter(),
                                query.get_projection(),
                                query.get_sort_by(),
                                query.skip,
                                query.limit)
        return success(results, "success")
    except Exception as e:
        return error(501, repr(e))


@router.get("/work_list/get_by_id/{_id}")
async def work_list_get_by_id(_id: str):
    try:
        return await get_dwm_by_id(work_list_collection, _id)
    except Exception as e:
        print(e)
        return error(501, repr(e))


@router.post("/work_list/save")
async def work_list_save(work_list: List[WorkListModel] = Body(...)):
    try:
        now = datetime.datetime.now()
        save_list = []
        id_set = set()
        for work_info in work_list:
            if work_info.work_id in id_set:
                return error(502, "存在重复的work_id：" + work_info.work_id)

            id_set.add(work_info.work_id)
            work_info.create_time = now
            work_info.latest_date = now.strftime("%Y%m%d%H%M%S%f")
            save_list.append(work_info.get_dict())
        return await bulk_write_dwm(work_list_collection, save_list)
    except Exception as e:
        print(e)
        return error(501, repr(e))


@router.post("/modify/get")
async def modify_get(query: QuerySchema = Body(...)):
    try:
        results = await get_dwm(modify_collection,
                                query.get_filter(),
                                query.get_projection(),
                                query.get_sort_by(),
                                query.skip,
                                query.limit)
        return success(results, "success")
    except Exception as e:
        return error(501, repr(e))


@router.get("/modify/get_by_id/{_id}")
async def modify_get_by_id(_id: str):
    try:
        return await get_dwm_by_id(modify_collection, _id)
    except Exception as e:
        print(e)
        return error(501, repr(e))


@router.post("/modify/{label}/save")
async def modify_save(modify_list: List[dict] = Body(...), label: str = None):
    try:
        now = datetime.datetime.now()
        save_list = []
        id_set = set()
        for modify_info in modify_list:
            if modify_info['_id'] in id_set:
                return error(502, "存在重复的_id：" + modify_info['_id'])

            id_set.add(modify_info['_id'])

            modify_info['update_date'] = now.strftime("%Y%m%d%H%M%S%f")
            _id = label + "_" + modify_info['_id'] + "_" + modify_info['update_date']
            user_id = modify_info.pop('user_id')
            user_name = modify_info.pop('user_name')
            save_info = {
                "_id": _id,
                "modify_id": modify_info['_id'],
                "label": label,
                "user_id": user_id,
                "user_name": user_name,
                "is_deprecated": modify_info['is_deprecated'],
                "update_date": modify_info['update_date'],
                "modify_info": modify_info
            }
            save_list.append(save_info)
        return await bulk_write_dwm(modify_collection, save_list)
    except Exception as e:
        print(e)
        return error(501, repr(e))
